package com.yuan.aicodemother.aop;

import com.yuan.aicodemother.annotation.AuthCheck;
import com.yuan.aicodemother.constant.UserConstant;
import com.yuan.aicodemother.exception.BusinessException;
import com.yuan.aicodemother.exception.ErrorCode;
import com.yuan.aicodemother.model.entity.User;
import com.yuan.aicodemother.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class AuthInterceptor {

    @Autowired
    private UserService userService;
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint pjp, AuthCheck authCheck) throws Throwable {
        //获取权限
        String userAuth = authCheck.value();
        //获取用户权限
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        User loginUser = userService.getLoginUser(request);
        String userRole = loginUser.getUserRole();
        //校验用户全新啊
        if (userRole == null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        if (UserConstant.ADMIN_ROLE.equals(userAuth) && !UserConstant.ADMIN_ROLE.equals(userRole)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //权限正确，放行
        return pjp.proceed();
    }
}
